package cn.tedu.tmall.front.account.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.front.account.dao.persist.repository.IUserRepository;
import cn.tedu.tmall.front.account.pojo.entity.User;
import cn.tedu.tmall.front.account.pojo.param.UserUpdateInfoParam;
import cn.tedu.tmall.front.account.pojo.vo.UserStandardVO;
import cn.tedu.tmall.front.account.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserRepository userRepository;

    @Override
    public void updatePassword(CurrentPrincipal currentPrincipal, String oldPassword, String newPassword) {
        Long userId = currentPrincipal.getId();
        UserStandardVO queryResult = userRepository.getStandardById(userId);
        String dbPassword = queryResult.getPassword();
        boolean matches = passwordEncoder.matches(oldPassword, dbPassword);
        if (!matches) {
            String message = "修改密码失败，原密码错误！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        String encodePassword = passwordEncoder.encode(newPassword);
        User user = new User();
        user.setId(userId);
        user.setPassword(encodePassword);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改密码失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateAvatar(CurrentPrincipal currentPrincipal, String avatar) {
        Long userId = currentPrincipal.getId();
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatar);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改头像失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateInfo(CurrentPrincipal currentPrincipal, UserUpdateInfoParam userUpdateInfoParam) {
        Long userId = currentPrincipal.getId();
        User user = new User();
        BeanUtils.copyProperties(userUpdateInfoParam, user);
        user.setId(userId);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = "修改基本信息失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

}
